import api from '../index'
import type { ResponseData, pageParam, RequestFromType, ResponseRowsRes } from '../type'
import type { OrderCouponsItem } from '.'
import type { MpPaymentParams } from '@/common/wxinit';

export type RequestGoodsListParams = pageParam & {
	orderByColumn ?: 'stockSold' | 'price' | null
	isAsc ?: 'desc' | 'asc' | ''
	subareaId ?: string
	groupingId ?: string,
	categoryId ?: string,
	name ?: string
}
export interface GoodsItem {
	id : string; //商品ID
	hasOwn : 0 | 1; //是否自营商品
	productCode : string; //商品编号
	stripeCode : string; //条码编号
	type : 1 | 2; //类型 1实物 2虚拟
	name : string; //名称
	shareMsg : string; //分享描述
	coverImg : string; //商品封面
	price : string; //价格
	priceScribing : string; //划线价
	deliveryMode : string; //支持的发货方式，包含哪个就支持哪个 1快递 2自提 3-闪送 4-核销 5-配送
	deliveryBillingMode : string; //快递计费方式 1统一 2运费模板
	deliveryFeeUnified : string; //统一运费 运费如果为0则是免运费
	deliveryFeeTempletName : string; //运费模板名称
	deliveryRemark ?: string; //物流备注
	hasPurchaseLimit ?: 1 | 0; //是否限购 1是 0否
	state : 1 | 2 | 3 | 4; //状态 1审核中 2仓库中 3销售中 4售罄
	stateApply : 2 | 3; //审核状态 2通过 3驳回
	applyRejectReason : string; //审核驳回原因
	createTime : string; //创建时间
	stockSold : number; //销量
	productSkuSpecificationList : {
		skuCode : string; //规格对象-编码
		stripeCode : string; //规格对象-条码
		skuSpec : string; //规格对象-规格名称
		weight : string; //规格对象-重量 KG
		stock : string; //规格对象-库存
		stockSold : string; //规格对象-库存已售
		price : string; //规格对象-销售价
		cost : number; //成本价
	}[];
	activity : {
		give ?: string;
		label ?: string;
		reduction ?: string;
		limit ?: string;
		discount ?: string;
		deduction ?: string;
		flashSale ?: string;
		coupon ?: string;
	}; //标签信息
	isFlash : 1 | 0; //是否支持闪送
	distributionType ?: 1 | 2; //1支持闪送，2z支持配送
}
// 商品列表
export const getGoodsList = (data : RequestGoodsListParams | { ids : string }) =>
	api.get<ResponseData<GoodsItem[], true>>('product/customer/list', {
		data,
		custom: {
			auth: false
		}
	}
	)
// 商品列表(猜你喜欢)
export const getPreferenceGoodsList = (data : pageParam) =>
	api.get<ResponseData<GoodsItem[], true>>('product/customer/preference/list',
		{
			data,
			custom: {
				auth: false
			}
		}
	)
// 优惠券可使用的商品列表
export const getProductByCouponId = (code : string, data : RequestGoodsListParams | { ids : string }) =>
	api.get<ResponseData<Array<GoodsItem & { stock : number }>, true>>(`customer/api/activity/coupon/product/page/${code}`, {
		data,
		custom: {
			auth: false
		}
	})
type RequestStoreListParams = pageParam & {
	industry ?: number
	orderByType ?: number
	orderByCollation ?: number
	beginTime ?: string
	endingTime ?: string
	keyword ?: string
}
export interface SearchStoreItem {
	averageScore : number
	distance : number
	evaluateCount : number
	id : string
	licenseAddrText : string
	logo : string
	name : string
	products : GoodsItem[]
	storeDescription : string
}

// 搜索店铺列表
export const getStoreList = (data : RequestStoreListParams) =>
	api.get<ResponseRowsRes<SearchStoreItem>>('merchant/customer/store/list',
		{
			data,
			custom: {
				auth: false
			}
		}
	)

export interface GoodsDetail {
	deliveryRemark ?: string; //配送描述
	deliveryBillingMode : 1 | 2; //运费计费模式 1统一运费 2运费模板
	deliveryFeeTempletName ?: string; //运费模板名称
	deliveryFeeUnified : number; //统一配送费(0则是包邮)
	deliveryMode : GoodsItem["deliveryMode"];
	distributionType : 0 | 1 | 2; //0-未匹配上 1-闪送 2-配送
	evaluateCount : number; //评价数量
	hasCollected : 0 | 1; //是否收藏 1是 0否
	hasOwn : 0 | 1; //是否自营商品 1是 0否
	hasWholesalePricing : 0 | 1; //是否批发定价 1是 0否
	id : string;
	minimumPurchaseQty : number; //起购数量
	maxNumber ?: number; //最大购买数量
	describes : string; //商品描述
	name : string;
	price : number; //售价
	priceMaximum ?: number; //批发定价-最小售价
	priceMinimum ?: number; //批发定价-最大售价
	priceScribing ?: number; //划线价
	productCode : string;
	productRightsInterests ?: Array<{ name : string; content : string }>; //服务描述
	shareMsg : string; //自定义分享文本
	state : 1 | 2 | 3 | 4; //状态 1审核中 2仓库中 3销售中 4售罄
	stockSold : number; //已售数量
	storeDeliveryScore : number; //店铺配送评分
	storeDescScore : number; //店铺描述评分
	storeHasOwn : 0 | 1; //是否自营店铺 1是 0否
	storeId : string;
	storeLogo : string;
	storeName : string;
	storeProductCount : number; //店铺商品数量
	storeServiceScore : number; //店铺服务评分
	subareaId : string;
	type : 1 | 2; // 1实物 2虚拟
	description : {
		detailRichTextMobile : string; //移动端商品富文本
		detailRichTextPc : string; //pc端商品富文本
		imgUrls : string; //商品图片列表
		videoUrl : string; //商品视频
	};
	activity : {
		give ?: string;
		label ?: string;
		reduction ?: string;
		limit ?: string;
		discount ?: string;
		deduction ?: string;
		flashSale ?: string;
		coupon ?: string;
	};
}
// 商品详情
export const getGoodsDetail = (data : { id : string }) =>
	api.get<ResponseData<GoodsDetail>>('product/customer/detail',
		{
			data,
			custom: {
				auth: false
			}
		}
	)
// 商品描述信息 已弃用，getGoodsDetail已返回该接口包含的数据，无需再额外请求
export const getGoodsDescription = (data : { productId : string }) =>
	api.get('product/customer/description',
		{
			data,
			custom: {
				auth: false
			}
		}
	)


type WholesalePricing = {
	minimum : number
	maximum : number
	pricing : number
}
export interface GoodsSkuSpecificationItem {
	id : string;
	price : number; //售价
	skuCoverImg : string; //封面图
	skuKey : string; //规格key
	skuSpec : string; //规格名称
	stock : number; //库存
	weight : number; //重量
	wholesalePricingRules ?: WholesalePricing[]; //批发定价
	productSkuValues : { id : number; name : string; productSkuNameId : number }[];
	priceScribing ?: number;
}
export interface GoodsSkuItem {
	id : number
	name : string
	productSkuValues : { id : number, name : string, productSkuNameId : number }[]
}

export interface GoodsSkuDetail {
	id : number
	productSkuSpecifications : GoodsSkuSpecificationItem[]
	productSkus : GoodsSkuItem[]
}
// 商品规格详情
export const getGoodsSkuDetail = (data : { productId : string }) =>
	api.get<ResponseData<GoodsSkuDetail>>('product/customer/sku/specification/detail',
		{
			data,
			custom: {
				auth: false
			}
		}
	)
export interface GoodsEvaluateItem {
	id : number;
	customerHeaderImg : string; //头像
	customerNickName : string; //名称
	averageScore : number; //评分
	createTime : string; //评价时间
	skuSpec : string; //商品规格信息
	content : string; //评价内容
	photos ?: string[]; //评价图片
	hasStoreReply : 0 | 1; //商家是否回复
	hasAnonym : 0 | 1;//是否匿名
	contentStoreReply : string; //商家回复内容
}
// 商品评价列表
export const getGoodsEvaluateList = (data : { productId : string } & pageParam) =>
	api.get<ResponseData<GoodsEvaluateItem[]> & { total : number }>('product/customer/evaluate/list',
		{
			data,
			custom: {
				auth: false
			}
		}
	)
export type GoodsEvaluateStatistics = {
	totalCount : number
	photoCount : number
	satisfactionRatio : number
}
// 商品评价统计
export const getGoodsEvaluateStatistics = (data : { productId : string }) =>
	api.get<ResponseData<GoodsEvaluateStatistics>>('product/customer/evaluate/list/statictics',
		{
			data,
			custom: {
				auth: false
			}
		}
	)

export type ClassifyItem = {
	icon : string
	id : number
	name : string
	sort : number
	type : 1 | 2,
	children?:ClassifyItem[]
}
// 商品一级分类 type 1 线上分类 2线下分类
export const getGoodsClassify = (data : { type : 1 | 2 | string, isPage ?: boolean } = { type: 1 }) =>
	api.get<ResponseData<ClassifyItem[]>>('system/api/category/tree',
		{
			data,
			custom: {
				auth: false
			}
		}
	)
// 商品二级分类
export const getGoodsClassifyTwo = (id : string | number) =>
	api.get<ResponseData<ClassifyItem[]>>(`system/api/category/tree/${id}`,
		{
			custom: {
				auth: false
			}
		}
	)
export enum PayType {
	SYS = "SYS",//系统支付
	STRIPE = "STRIPE",//STRIPE
	WX = "WX",//微信支付
	ZFB = "ZFB",//支付宝
	OFFLINE = "OFFLINE",//线下支付
	CASH = "CASH",//货到付款
	CYBERSOURCE = "CYBERSOURCE"//CYBERSOURCE
}
export interface PaymodeItem {
	icon : string
	name : string
	id : number
	isDefault : 'Y' | 'N',
	type : PayType
	subPayType : string
	money : number
}
// 支付列表
export const getPaymode = (data : {
	doType : string,
	payType : string,
	proIds ?: string
	fromType : RequestFromType,
	isDefault ?: 'Y' | 'N',
	type?:string|number//传1为线上商家商品支付，传2为线下商家商品或买单支付
}) =>
	api.get<ResponseData<PaymodeItem[]>>('system/api/paymode/list', {
		data,
		custom: {
			isLoading: true
		}
	})

export interface PreviewGoodsOrderParams {
	receivedId ?: number | string
	receivingType : number
	couponShareCode ?: string
	groupCode ?: string
}
// 单商品下单预览
export interface PreviewOneGoodsOrderParams {
	qty : string;
	skuId : string;
	receivedId ?: number;
	receivingType : number;
	couponShareCode ?: string;
	groupCode ?: string;
}
export interface DeductionStrategy {
	check : boolean
	strategy : string
	name : string
	icon : string
	id : number
	deductMoney : number
	floatingMoney : number
}
export interface OrderGoods {
	fig ?: string
	orderMoney : number
	orderDeliveryfee : number
	orderMoneyPay : number,
	orderMoneyDis : number
	orderMoneyCoupon : number
	orderMoneyDeduction : number
	orderFreight : number,
	orderTitle : string
	storeId : string
	storeName : string
	location:string
	orderCost : number
	verifyCode ?: string,
	storeLogo : string
	storeHasOwn : 1 | 0,
	deputys : Array<{
		commodityId : string
		commodityUrl : string
		commodityCount : number
		commodityCost : number
		commoditySupplierCost : number
		commodityFreight : number
		commoditySpecId : string
		commodityName : string
		commoditySpecName : string
		deputyMoney : number
		deputyMoneyPay: number
		deputyMoneyDeduction : number //商品抵扣金额
		basketId ?: string,
		type : 1 | 2//1 实物 2虚拟物品
		isFlash : 1 | 0//是否支持下单
		flashDeliveryLimit ?: number
		params ?: {
			deductionStrategy : DeductionStrategy[]
		}
	}>
	params ?: {
		coupon ?: {
			couponList : OrderCouponsItem[]
		}
		deductionStrategy ?: DeductionStrategy[]
	}

}
export interface PreviewOrderData {
	orderVos : OrderGoods[];
	storeReceiving : boolean;
	money : number;
	moneyDis : number;
	payMoney : number;
	freight : number; //运费
	moneyDeduction : number;
	couponMoney : number; //店铺优惠
	couponMoneySys : number; //平台优惠
	deliveryfee : number; //配送费
	deliveryDay ?: string;
	// deliveryTomorrow: null,
	deliveryModes : string[];
	delivery : boolean;
	formFee ?: number; //订单内包含表单商品的时，表单的金额总计
}

export const postPreviewOneGoodsOrder = (data : PreviewOneGoodsOrderParams) =>
	api.post<ResponseData<PreviewOrderData>>('customer/api/order/create/one/pre',
		{
			data
		}
	)

export interface PurchaseGoodsParams {
	receivingId ?: number | string,
	couponId ?: string
	receivingType : number,
	couponShareCode ?: string
	virtuallyProPhone ?: string
	deliveryTimes ?: string
	receivingIds ?: string
	remarks ?: string
	deductionStrategy ?: string
	fromType ?: RequestFromType,
	receivedId ?: string | number
	payId : number
	payword ?: string
	deliveryRemark ?: string
	traceId ?: string
	hasInvoice?:number
	orderInvoicesStr?:string
}
export interface JinQianBaPayData {
	code:number,
	data:{
		payOrderId: string;
		mchOrderNo: string;
		payData: string;
		payDataType: string;
		orderState: number;
	},
	fail:boolean,
	ok:boolean,
	sign:string
	originalId:string
	appid:string
	payType:'CASHIER_ALIH5'|'CASHIER_ALIAPP'|'CASHIER_WXH5'|'CASHIER_WXAPP'|'QR_CASHIER'|'WX_JSAPI'
}

export interface PurchaseGoodsPayData<T = any> extends Omit<ResponseData, 'data'> {
	paycode : string
	data : T
	state ?: string
	orderId : string
	payMoney : number
}
// 单商品购买
export const postPurchaseOneGoods = (data : PurchaseGoodsParams & {
	skuId : string,
	qty : string,
}) =>
	api.post<PurchaseGoodsPayData>('customer/api/order/create/one', {
		data,
		custom: {
			getError: true,
			isLoading:true
		}
	})

export interface PreviewCartGoodsOrderParams extends PreviewGoodsOrderParams {
	basketIds : string
}
// 购物车商品下单预览
export const postPreviewCartGoodsOrder = (data : PreviewCartGoodsOrderParams) =>
	api.post<ResponseData<PreviewOrderData>>('customer/api/order/create/basket/pre', {
		data
	})

// 购物车商品购买
export const postPurchaseCartGoods = (data : PurchaseGoodsParams & { basketIds : string }) =>
	api.post<PurchaseGoodsPayData>('customer/api/order/create/basket', {
		data,
		custom: {
			getError: true,
			isLoading:true
		}
	})

// 重新支付的订单预览
export interface PreviewAgainCreateGoodsParams extends PreviewGoodsOrderParams {
	buys : string
}

export const postAgainCreateGoods = (data : PreviewAgainCreateGoodsParams) =>
	api.post<ResponseData<PreviewOrderData>>('customer/api/order/create/multiple/pre', {
		data
	})
// 订单重新支付或批发支付
export const postAgainPurchaseGoods = (data : PurchaseGoodsParams & { buys : string }) =>
	api.post<PurchaseGoodsPayData>('customer/api/order/create/multiple', {
		data,
		custom: {
			getError: true,
			isLoading:true
		}
	})


// 支付结果查询
export const getPayResult = (id : string) =>
	api.get<PurchaseGoodsPayData>(`order/api/main/payCode/${id}`)
// 小程序商品分享二维码链接地址
export const getGoodsShareUrl = (data : {
	url : string
	formType : RequestFromType
	scene ?: string
}) =>
	api.post<{
		shareUrl : string
		code : number,
		msg : string
	}>('customer/api/commodity/share/pre', {
		data
	})

// 获取自提点
export const getStoreAddressList = (data : {
	storeId : string
	addrLatitude : number
	addrLongitude : number
	addrDetail : string
} & pageParam) =>
	api.get(`merchant/customer/store/address/list`, {
		data
	})
export interface DeliveryPlace {
	id : string
	storeId : string
	labelName : string
	labelTextColor : string
	labelBackgroundColor : string
	name : string
	detailedAddress : string
	distance : number
	businessHours : string
	location : string
	deliveryAddressText : string
}
//获取店铺自提点列表
export const getDeliveryPlaceList = (data : { storeId ?: string, location : string, key ?: string }) => {
	return api.get<ResponseData<DeliveryPlace[]>>('merchant/express/getDeliveryPlaceList', {
		data,
		custom: {
			isLocation: true
		}
	})
}
export interface GoodsAppointmentStaffsClassItem {
	staffCount : number
	id : number
	storeId : string
	name : string
	beginTime : string
	endTime : string

}
export interface GoodsAppointmentStaffsItem {
	remark : string
	id : number,
	storeId : string
	staffNickname : string
	staffPhone : string
	staffJob : string
	staffSex : number
	staffHead : string,
	state : number
	serviceIds : string
	params : {
		data : {
			day : string
			classList ?: GoodsAppointmentStaffsClassItem[]
		}[]
	},


}
export interface GoodsAppointmentInfo {
	appointmentMoney : number
	appointmentType : string
	price : number,
	staffsList ?: GoodsAppointmentStaffsItem[]
}
//获取服务商品的可预约信息
export const getGoodsAppointmentInfo = (id : number | string) =>
	api.get<ResponseData<GoodsAppointmentInfo>>(`merchant/customer/appointment/service/${id}`)

export interface AppointmentPreviewGoodsOrderParams {

}

export interface AppointmentPreviewOrderData {
	servicePhoto : string
	serviceName : string
	serviceSpec : string
	servicePrice : string
	moneyAll : number//总价
	payMoney : number//支付金额
	staffName : string//员工名称
	appointmentType : 1 | 2//服务类型
	appointmentMoney : number//上门费
	appointmentTime : string//上门时间
	appointmentTimeStr : string//上门时间
	addressDetail : string//上门地址
}
//服务商品下单预览
export const getGoodsAppointmentPreviewOrderInfo = (data : AppointmentPreviewGoodsOrderParams) =>
	api.get<ResponseData<AppointmentPreviewOrderData>>('customer/api/appointment/order/pre', {
		data
	})
//服务商品下单
export const postPurchaseGoodsAppointment = (data : AppointmentPreviewGoodsOrderParams) =>
	api.post<PurchaseGoodsPayData>('customer/api/appointment/order', {
		data
	})
export interface GoodsTimeCardItem {
	id : number
	headline : string//	次卡标题
	price : string//	价格
	exchangeSize : string//	兑换次数
	isEffective : string//	0-到期失效 1-永久有效
	effectiveTime : string//	有效期
	isRf : string//	0-不限制兑换频率 1-限制兑换频率
	limitDays : string//	频率 限制天数
	limitNumber : string//	频率 限制次数
	background : string//	背景色
	backgroundUrl : string//	背景图
}
// 商品绑定的次卡列表
export const getGoodsTimeCardList = (data : { skuId : string | number }) =>
	api.get<ResponseData<GoodsTimeCardItem[]>>('merchant/customer/seqcard/proList', {
		data,
		custom: {
			auth: false
		}
	}
	)
export interface PurchaseTimeCardParams {
	fromType ?: RequestFromType,
	payId : number
	cardId : number | string,
	payword ?: string
}
//购买次卡
export const postPurchaseTimeCard = (data : PurchaseTimeCardParams) =>
	api.post<PurchaseGoodsPayData>('customer/api/order/card/buy', {
		data,
		custom: {
			showMsg: true
		}
	})
// 转聊快捷支付
export const postZlCardConfirmPayment = (data: { code: string; data: string }) =>
	api.post('/customer/api/order/zl/confirm/payment', {
		data,
		custom: {
			getError: true,
			isLoading: true
		}
	});

export interface GoodsForm {
  id: number;
  title: string; //标题，纯文本
  titleText: string; //标题，富文本
  illustrate: string; //说明
  backUrl: string; //表单图片
  color: string; //header颜色
  backColour: string; //背景颜色
  subNum: number; //提交次数限制
  endType: number; //结束类型 1永久 2定期 3定量
  endVle: string; //endType为2时，是时间格式字符串，代表结束时间，endType为3时，代表最大提交表单量
  formOptions: GoodsFormOption[];
  isHiddNumber: 0 | 1; //是否显示问题前面的序号 0为显示
}
//获取商品表单
export const getGoodsForm = (data: { proId: string }) =>
  api.get<ResponseData<GoodsForm>>("customer/api/form/get", {
    data,
    custom: {
      auth: false,
    },
  });
